import { post, get } from '@/api/ajax'
import { UserApi } from '@/api/apis'
import { Commit } from 'vuex'
import { setToken, getToken, clearToken } from '@/utils/auth'
import AccountModel from '@/models/AccountModel'
import { LoginQueryType, UserStateType, ChangePassType } from './types'
import ArticleModel from '@/models/ArticleModel'

const initState: UserStateType = {
  // 用户名
  name: '',
  // token
  token: getToken(),
  // 用户类型
  type: undefined
}

const SET_TOKEN_FUNC = (state: UserStateType, token?: string) => {
  state.token = token || ''
  token ?  setToken(token) : clearToken()
}

const mutations = {
  // 设置用户数据
  SET_USER_INFO: (state: UserStateType, userInfo: AccountModel) => {
    if (userInfo) {
      state.name = userInfo.name
      state.type = userInfo.type
    } else {
      state.name = ''
      state.type = undefined
      SET_TOKEN_FUNC(state)
    }
  },
  // 设置用户数据
  SET_TOKEN: (state: UserStateType, token?: string) => {
    SET_TOKEN_FUNC(state, token)
  },
}

const actions = {
  // 登录
  LOGIN(context: { commit: Commit }, data: LoginQueryType) {
    return new Promise((resolve, reject) => {
      post<AccountModel>(UserApi.login, data).then((resData: AccountModel) => {
        context.commit('SET_USER_INFO', resData)
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 获取用户信息
  GET_USER_INFO(context: { commit: Commit }) {
    return new Promise((resolve, reject) => {
      get<AccountModel>(UserApi.sessionLogin).then((resData: AccountModel) => {
        context.commit('SET_USER_INFO', resData)
        if (resData.currentProject) {
          const projectModel = new ArticleModel()
          projectModel.setDataWithJson(resData.currentProject)
          context.commit('SET_PROJECT', projectModel)
        }
        resolve()
      }).catch((err) => {
        context.commit('SET_USER_INFO')
        reject(err)
      })
    })
  },
  // 修改密码
  CHANGE_PASSWORD(context: { commit: Commit }, data: ChangePassType) {
    return new Promise((resolve, reject) => {
      post(UserApi.updatePass, data).then(() => {
        context.commit('SET_USER_INFO')
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 登出
  LOG_OUT(context: { commit: Commit }) {
    return new Promise((resolve, reject) => {
      get(UserApi.logut).then(() => {
        context.commit('SET_USER_INFO', null)
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 前端 登出
  FED_LOG_OUT(context: { commit: Commit }) {
    context.commit('SET_USER_INFO')
  },
}

export default {
  state: initState,
  actions,
  mutations,
}
